#!/usr/bin/env python
#encoding=utf-8
import re
import sys
import time
import email
import imaplib
import smtplib
from email.mime.text import MIMEText

import log
from config import config
from base import base

class mail(base):
	
	def __init__(self, conf):
		super(mail, self).__init__()
		self._user = conf.get('user')
		self._password = conf.get('password')
		self._maildir = conf.get('maildir')
		self._smtpserver = conf.get('smtpserver')
		self._imapserver = conf.get('imapserver')
		self._maillist = conf.get('maillist')
		self._port = 993

		# save not match mail subject in case sb not follow
		# the mail rule
		self._not_match_mail_sb = []
		self._match_mail_list = []

	def get_mailmsgs(self, subject):
		'''
		get mail obj
		'''
		match_mailmsgs = []
		not_match_mail_sb= []
		
		number = 0
		
		p = imaplib.IMAP4_SSL(self._imapserver, self._port)
		p.login(self._user, self._password)
		p.select(self._maildir)	
		
		# Read Unseen mail
		# Marked as seen
		# Find $subject and mark Flagged
		mailresp, mailitmes = p.search(None, "UNSEEN")
		for num in mailitmes[0].split():
			typ, data = p.fetch(num, '(BODY.PEEK[])')
			
			mailText = data[0][1]
			mail_message = \
			              email.message_from_string(mailText)
			              
			number += 1
			# find subject
			mail_subject = mail_message['subject']
			if re.search(subject, mail_subject):
				#print mail_message.as_string()
				match_mailmsgs.append(mail_message)
				self.logger.debug('Get a mail :[%s]' % mail_subject)
				self.logger.debug("Flagged [%s]" \
								 % mail_subject)
				# set Flag
				p.store(num, '+FLAGS','\\Flagged')
				#we need to mark it as Seen after fetching
				p.store(num, '+FLAGS','\\Seen')
			else:
				# not match the rule
				not_match_mail_sb.append(mail_subject)
				self.logger.debug("[%s] not match rules, mark as seen"\
                                                 % mail_subject)
				p.store(num, '+FLAGS','\\Seen')
			
		p.close()
		p.logout()
		
		self.logger.info("received [%d] mail(s)" % \
		                                               number)
		self.logger.info("[%d] mail(s) match the rule" % \
		                                               len(match_mailmsgs))

		self._match_mail_list = match_mailmsgs
		self._not_match_mail_sb = not_match_mail_sb
		return (match_mailmsgs, not_match_mail_sb)

		# we need to send a mail to tell log
	def send_mail(self, subject, msg):
		s_msg = MIMEText(msg)
		s_msg['Subject'] = subject
		s_msg['To'] = self._maillist
		s = smtplib.SMTP(self._smtpserver)
		s.sendmail(self._user + '@linux.vnet.ibm.com', \
		                         self._maillist, s_msg.as_string())
		s.quit()

if __name__ == "__main__":
	# 
	c = config()
	m = mail(c)
	
	#m.send_mail("hello")
	objs = m.get_mailmsgs('^\[Frobisher\] \[')
	for obj in objs:
		print obj
